package com.educhains.web.ctrl.backend;


import com.alibaba.fastjson.JSONObject;


import com.educhains.module.course.service.CourseUploadService;
import com.educhains.module.course.vo.Course;
import com.educhains.module.course.vo.CourseChapter;
import com.educhains.module.course.vo.CourseChapterFile;
import com.educhains.web.util.FileUploadUtils;
import com.educhains.web.util.JsonUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class CourseCtrl {

    private static final String  TYPE_PATH = "/WEB-INF/jsp/backend/maintain/coursePage.jsp";
    private static final String  TYPE_PATHC = "/WEB-INF/jsp/backend/maintain/coursePageForCheck.jsp";
    private static final String  TYPE = "course";
    private static final String  TYPEC = "courseCheck";

    @Autowired
    private CourseUploadService courseUploadService;





    @RequestMapping(value = "/maintain/courseManage")
    public String courseManage(HttpServletRequest request) {


//        String titleFragment = request.getParameter("title_fragment");
//        String pageNum = request.getParameter("p") == null ? "1" : request.getParameter("p");
//
//        Page postPage;
//        if(titleFragment == null || titleFragment.equals("") || titleFragment.equals("undefined")) {
//            postPage = postService.showPostPage(Integer.valueOf(pageNum), 1);
//        } else {
//            postPage = postService.searchByTitlePage(Integer.valueOf(pageNum),titleFragment);
//        }

        request.setAttribute("type", TYPE);
        request.setAttribute("typePath", TYPE_PATH);
//        request.setAttribute("postPage", postPage);
//        request.setAttribute("titleFragment", titleFragment);

        return "backend/maintain/operationPanel";
    }

    @RequestMapping(value = "/maintain/courseManageCheck")
    public String courseManageCheck(HttpServletRequest request) {


//        String titleFragment = request.getParameter("title_fragment");
//        String pageNum = request.getParameter("p") == null ? "1" : request.getParameter("p");
//
//        Page postPage;
//        if(titleFragment == null || titleFragment.equals("") || titleFragment.equals("undefined")) {
//            postPage = postService.showPostPage(Integer.valueOf(pageNum), 1);
//        } else {
//            postPage = postService.searchByTitlePage(Integer.valueOf(pageNum),titleFragment);
//        }

        request.setAttribute("type", TYPEC);
        request.setAttribute("typePath", TYPE_PATHC);
//        request.setAttribute("postPage", postPage);
//        request.setAttribute("titleFragment", titleFragment);

        return "backend/maintain/operationPanel";
    }


    @ResponseBody
    @RequestMapping(value = "/maintain/courseAdd")
    public String courseAdd(HttpServletRequest request) {

        String courseName = request.getParameter("course_name");
        String courseIntro = request.getParameter("course_intro");
        String courseDiff = request.getParameter("course_diff");
        String courseStime = request.getParameter("course_stime");
        String courseEtime = request.getParameter("course_etime");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date sdate = null;
        Date edate = null;
        try {
            sdate = sdf.parse(courseStime);
            edate = sdf.parse(courseEtime);
        } catch (ParseException e) {
            e.printStackTrace();
            return returnBody(false, "time problem");
        }

        String courseTid = request.getParameter("course_tid");
        String courseTname = request.getParameter("course_tname");
        String courseTmsg = request.getParameter("course_tmsg");


        Date now = new Date();
        //FIXME time_id replace acticity_id temply ,
        long time_id = System.currentTimeMillis();

        Course course = new Course();

        // 位数问题，time_id是13位，int数据库最大11位
        course.setCourseId((int) (time_id/1000));
        course.setCourseName(courseName);
        course.setCourseIntroducton(courseIntro);
        course.setCourseDifficulty(courseDiff);
        course.setCourseStartTime(sdate);
        course.setCourseEndTime(edate);
        course.setCourseTeacherId(courseTid);
        course.setCourseTeacherName(courseTname);
        course.setCourseTeacherMessage(courseTmsg);

        courseUploadService.CourseUpload(course);


        return returnBody(true, "modify successfully");
    }

    @ResponseBody
    @RequestMapping(value = "/maintain/courseVideoUpload")
    public String courseVideoUpload(HttpServletRequest request,
                                    @RequestParam(value = "course_video") MultipartFile videoFile) throws Exception  {


        String realPath = request.getSession().getServletContext().getRealPath("/");
        String fileName = videoFile.getOriginalFilename();

//        System.out.println("realPath: " + realPath);
//        System.out.println("fileName: " + fileName);
//        System.out.println("videoFile.getContentType(): " + videoFile.getContentType());

        String resourcePath = "resources/uploadVideos/";
        if(FileUploadUtils.allowUploadTeacherUpload(videoFile.getContentType())) {
            File dir = new File(realPath + resourcePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, fileName);
            videoFile.transferTo(file);

        }else {
            return returnBody(true, "fileType should be \"ZIP or RAR\"");
        }
        return returnBody(true, "modify successfully");
    }

    @ResponseBody
    @RequestMapping(value = "/maintain/courseChapterUpload")
    public String courseChapterUpload(HttpServletRequest request) throws Exception  {

        String courseId = request.getParameter("course_id");
        String chapterName = request.getParameter("chapter_name");
        String chapterIntro = request.getParameter("chapter_introduction");
//        String courseRest = request.getParameter("course_rest");

        long time_id = System.currentTimeMillis();

        CourseChapter courseChapter = new CourseChapter();
        courseChapter.setCourseId(Integer.valueOf(courseId));
        courseChapter.setChapterId((int) (time_id/1000));
        courseChapter.setChapterName(chapterName);
        courseChapter.setChapterIntroduction(chapterIntro);

        courseUploadService.CourseChapterUpload(courseChapter);


        return returnBody(true, "modify successfully");
    }

    @ResponseBody
    @RequestMapping(value = "/maintain/courseChapterFileUpload")
    public String courseChapterFileUpload(HttpServletRequest request,
                                    @RequestParam(value = "course_chapter_file") MultipartFile chapterFile) throws Exception  {

        String chapterName = request.getParameter("chapter_name");


        String realPath = request.getSession().getServletContext().getRealPath("/");
        String fileName = chapterFile.getOriginalFilename();

//        System.out.println("realPath: " + realPath);
//        System.out.println("fileName: " + fileName);
//        System.out.println("videoFile.getContentType(): " + chapterFile.getContentType());

        String resourcePath = "resources/chapterUpload/";

        String chapterFilePath = realPath + resourcePath;
        Integer chapterId = courseUploadService.findChapterIdByName(chapterName);

        CourseChapterFile courseChapterFile = new CourseChapterFile();
        courseChapterFile.setChapterId(chapterId);
        courseChapterFile.setChapterFileName(fileName);
        courseChapterFile.setChapterFilePath(chapterFilePath);




        File dir = new File(realPath + resourcePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, fileName);
        chapterFile.transferTo(file);

        courseUploadService.CourseChapterFileUpload(courseChapterFile);

//        return returnBody(true, "fileType should be \"ZIP or RAR\"");

        return returnBody(true, "modify successfully");
    }

    private static String returnBody(boolean success, String msg) {
        JSONObject json = new JSONObject();
        if (success) {
            json.put("success", true);
            json.put("msg", msg);
        } else {
            json.put("success", false);
            json.put("msg", msg);
        }
        //return json.toJSONString();
        return JsonUtils.toJSONString(json);
    }
}
